const app = getApp()
const to = app.require("lib/awaitTo")
const upload = app.require("lib/upload")
const cloudFunc = app.require("lib/cloudFunc")
const db = wx.cloud.database()

module.exports = {
	data: {
		user: wx.getStorageSync('user'),
	},
	async login() {
		const [err, userRes] = await to(wx.getUserProfile({
			desc: '用于存储用户数据'
		}), "getUserProfile")
		if (err) {
			wx.hideLoading()
			wx.showToast({
				title: '登录失败',
				icon: "none"
			})
			return
		}
		wx.showLoading({
			mask: true,
			title: '登录中'
		})
		const loginRes = await cloudFunc("user/login")
		const user = await db.collection("user").get({
			openid: loginRes.result.openid
		})
		if (!user.data.length) {
			wx.downloadFile({
				url: userRes.userInfo.avatarUrl,
				success: async downloadRes => {
					const uploadRes = await upload(downloadRes.tempFilePath)
					userRes.userInfo = {
						...userRes.userInfo,
						avatarUrl: uploadRes.fileID,
						intro: "",
						fans: [],
						fansNum: 0,
						createTime: new Date().getTime()
					}
					wx.hideLoading()
					await db.collection("user").add({
						data: userRes.userInfo
					})
					wx.setStorageSync('user', userRes.userInfo)
					this.setData({ user: userRes.userInfo })
					this.selectComponent("#left-bar").getUser()
					app.watchMessage()
					wx.showToast({
						title: '登录成功',
						icon: "none"
					})
				}
			})
		}
		else {
			wx.setStorageSync('user', user.data[0])
			this.setData({ user: user.data[0] })
			this.selectComponent("#left-bar").getUser()

			wx.hideLoading()
		}
	},
}